package org.dingyom.gift.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService;
import org.springframework.security.oauth2.provider.code.AuthorizationCodeServices;
import org.springframework.security.oauth2.provider.code.JdbcAuthorizationCodeServices;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.TokenEnhancerChain;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.InMemoryTokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;

import javax.sql.DataSource;
import java.util.Arrays;

//授权服务配置
@Configuration
//开启授权服务配置
@EnableAuthorizationServer
public class MyAuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
    private static final String SIGN_KEY = "dingyom_gift_afslkfslahfsd";

    @Autowired
    private DataSource dataSource;
    @Autowired
    private PasswordEncoder passwordEncoder;
    //一.客户端详情配置
    @Bean
    public ClientDetailsService clientDetailsService(){

        JdbcClientDetailsService clientDetailsService =
                new JdbcClientDetailsService(dataSource);

        //配置密码比对器，匹配client_secret
        clientDetailsService.setPasswordEncoder(passwordEncoder);
        return clientDetailsService;
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
       clients.withClientDetails(clientDetailsService()); //方法注入
    }

    @Autowired
    private AuthenticationManager authenticationManager;
    //二.授权服务端点配置
    @Bean
    public AuthorizationCodeServices authorizationCodeServices(){
        return new JdbcAuthorizationCodeServices(dataSource);
    }

    @Bean
    public TokenStore tokenStore(){
        //return new InMemoryTokenStore(); //暂时不用数据库和redis，因为后面要jwttoken不需要存储
        return new JwtTokenStore(jwtAccessTokenConverter());
    }

    /**
     *
     * @return
     */
    @Bean
    public JwtAccessTokenConverter jwtAccessTokenConverter() {
        JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
        converter.setSigningKey(SIGN_KEY);//设置JWT签名秘钥
        return converter;
    }

    //配置令牌管理服务
    @Bean
    public AuthorizationServerTokenServices tokenServices(){
        DefaultTokenServices tokenServices = new DefaultTokenServices();
        tokenServices.setClientDetailsService(clientDetailsService()); //设置客户端详情
        tokenServices.setSupportRefreshToken(true);//支持刷新token
        tokenServices.setTokenStore(tokenStore()); //token存在方式

        //设置token增强 - 设置token转换器
        TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
        tokenEnhancerChain.setTokenEnhancers(Arrays.asList(jwtAccessTokenConverter()));
        tokenServices.setTokenEnhancer(tokenEnhancerChain);  //jwtAccessTokenConverter()

        //token有效时间2小时
        tokenServices.setAccessTokenValiditySeconds(72000);
        //属性令牌默认有效时间
        tokenServices.setRefreshTokenValiditySeconds(200000);
        return tokenServices;
    }
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints
                .authenticationManager(authenticationManager) //密码授权模式需要
                .authorizationCodeServices(authorizationCodeServices())//授权码
                .tokenServices(tokenServices()) //通过它可以产生token
                .allowedTokenEndpointRequestMethods(HttpMethod.POST);   //允许post方式请求
    }

    //三.授权服务安全配置
    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        //校验token的地址放行
        security.checkTokenAccess("permitAll()")
                .allowFormAuthenticationForClients();// 允许客户端进行表单身份验证,使用表单认证申请令牌
    }
}
